<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<!-- Head -->

<head>
  <meta charset="utf-8" />
  <title></title>

  <div th:replace="/system/resource/base/baseHead.template"></div>
  <link rel="stylesheet" type="text/css" th:href="${application.resourceUrl}+'/assets/js/lightbox/css/lightbox.css'" />
  <link rel="stylesheet" type="text/css" href="https://cdn.test.bestpay.net/orange/antd.1.6.5.css" />
  <!-- <link rel="stylesheet" type="text/css" href="./antd.1.6.5.css" /> -->
  <link rel="stylesheet" type="text/css" href="https://cdn.test.bestpay.net/orange/tailwindcss@2.2.19.min.css" />
  <style>
    html {
      font-size: 14px;
    }

    .page-body {
      padding: 30px;
    }

    .ant-card {
      margin-bottom: 20px;
    }

    [v-cloak] {
      visibility: hidden;
    }

    .goods-info-title-icon {
      cursor: pointer;
      font-size: 30px;
      position: relative;
      left: 0px;
      top: 5px;
    }

    .dialog-form-product-info {
      display: flex;
    }

    .dialog-form-product-info-scenevos {
      margin-left: 20px;
    }
  </style>
</head>
<!-- /Head -->
<!-- Body -->

<body>
  <!-- 引入头部 -->
  <div th:include="/system/resource/base/baseNav.template"></div>
  <!-- /引入头部 -->
  <!-- Main Container -->
  <div class="main-container container-fluid">
    <!-- Page Container -->
    <div class="page-container">
      <!-- 引入左侧菜单 -->
      <div class="page-sidebar" id="sidebar" th:include="/system/resource/base/baseLeftMenu.template"></div>
      <!-- /引入左侧菜单 -->
      <!-- Page Content -->
      <div class="page-content">
        <!-- Page Breadcrumb -->
        <div class="page-breadcrumbs">
          <ul class="breadcrumb"></ul>
        </div>
        <!-- /Page Breadcrumb -->
        <!-- Page Body -->
        <div id="app" class="page-body" v-cloak>
          <div v-if="showTablePage">
            <a-card title="商家信息-查询">
              <a-form-model id="tableForm" :model="form" v-bind="layout">
                <a-row :gutter="24">
                  <a-col :span="10">
                    <a-form-model-item label="商家ID :">
                      <a-input v-model="form.merchantId" placeholder="请输入商家ID" />
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="12">
                    <a-form-model-item label="商家名称 :">
                      <a-input v-model="form.merchantName" placeholder="请输入商家名称" />
                    </a-form-model-item>
                  </a-col>
                </a-row>
                <form id="query-form" method="post" style="display: none;">
                  <input type="text" name="query.blindBoxId" :value="form.merchantId">
                  <input type="text" name="query.subOrderNo" :value="form.merchantNo">
                  <input type="text" name="query.orderNo" :value="form.merchantName">
                </form>

                <a-row>
                  <a-col :span="24" :style="{ textAlign: 'center' }">
                    <a-button type="primary" :loading="queryTableLoading" @click="onQueryTableData">
                      查询
                    </a-button>
                    <a-button :style="{ marginLeft: '8px' }" @click="resetSearchFormInfo">
                      重置
                    </a-button>
                  </a-col>
                </a-row>
              </a-form-model>
            </a-card>
            <a-card title="查询结果">
              <a-button @click="onAddActivity" slot="extra" type="primary">
                新增
              </a-button>
              <a-config-provider :locale="locales.zh_CN">

                <a-table :columns="tableColumns" :data-source="tableData" :loading="loading" :pagination="pagination"
                  row-key="id" :scroll="tableScroll" bordered size="small" @change="handleTableChange">
                  <template slot="action" slot-scope="text, record, index">
                    <a-button type="primary" @click="showDetailDialog(record)">详情</a-button>
                    <a-button type="primary" @click="showDetailDialog(record)">修改</a-button>

                    <a-button type="primary" @click="showDetailDialog(record)">删除</a-button>
                  </template>
                </a-table>
              </a-config-provider>
            </a-card>
          </div>
          <div v-else>
            <a-form-model layout="inline" ref="ruleForm" :model="dialogForm">
              <a-card title="新增商家信息">
                <a-row :gutter="24">
                  <a-col :span="1"></a-col>
                  <a-col :span="7">
                    <a-form-model-item prop="merchantName" :rules="dialogFormRules.merchantName" label="商家名称 :">
                      <a-input :disabled="dialogFormDisabled" v-model="dialogForm.merchantName" />
                    </a-form-model-item>
                  </a-col>
                </a-row>
                <a-row v-for="(item,index) in dialogForm.ProductInfoVO" :key="index" :gutter="24">
                  <a-col :span="1"></a-col>
                  <a-col class="dialog-form-product-info" :span="23">
                    <a-form-model-item :prop="'ProductInfoVO.' + index + '.productName'"
                      :rules="dialogFormRules.productName" label="所属产品 :">
                      <a-input :disabled="dialogFormDisabled" v-model="item.productName" />
                    </a-form-model-item>
                    <a-icon v-if="!index" type="plus-square" @click="onAddMerchantName(index)"
                      class="goods-info-title-icon"></a-icon>
                    <a-icon v-else @click="onDelMerchantName(index)" type="minus-square"
                      class="goods-info-title-icon"></a-icon>
                    <div class="dialog-form-product-info-scenevos">
                      <div v-for="(child,i) in item.sceneVOs" :key="i">
                        <a-form-model-item :prop="'ProductInfoVO.' + index + '.sceneVOs.' + i + '.sceneName'"
                          :rules="dialogFormRules.sceneName" label="场景 :">
                          <a-input :disabled="dialogFormDisabled" v-model="child.sceneName" />
                        </a-form-model-item>
                        <a-icon v-if="!i" type="plus-square" @click="onAddMerchantSceneVOs(index,i)"
                          class="goods-info-title-icon"></a-icon>
                        <a-icon v-else @click="onDelMerchantSceneVOs(index,i)" type="minus-square"
                          class="goods-info-title-icon"></a-icon>
                      </div>
                    </div>
                  </a-col>
                </a-row>
                <a-row type="flex" justify="center">
                  <!-- v-if="isEdit || !dialogFormDisable"  -->
                  <a-button size="large" type="primary" :loading="editBtnLoading" @click="onSubmit(true)">
                    确认
                  </a-button>
                  <a-button @click="dialogButtonClick(false)" size="large">
                    返回
                  </a-button>
                </a-row>
              </a-card>
            </a-form-model>
          </div>
        </div>
      </div>
    </div>
    <!-- /Page Body -->
  </div>
  <!-- /Page Content -->
  <div th:replace="/system/resource/base/baseFoot.template"></div>

  <script
    th:src="${application.resourceUrl}+'/assets/js/datatable/jquery.dataTables.min.js?'+${application.JSVERSION}"></script>
  <script
    th:src="${application.resourceUrl}+'/assets/js/datatable/dataTables.tableTools.min.js?'+${application.JSVERSION}"></script>
  <script
    th:src="${application.resourceUrl}+'/assets/js/datatable/dataTables.bootstrap.min.js?'+${application.JSVERSION}"></script>
  <script th:src="${application.resourceUrl}+'/bboss/js/datatable/DT_bootstrap.js?'+${application.JSVERSION}"></script>
  <script
    th:src="${application.resourceUrl}+'/assets/js/validation/bootstrapValidator.js?'+${application.JSVERSION}"></script>
  <script
    th:src="${application.resourceUrl}+'/assets/js/validation/bootstrapValidator_zh_CN.js?'+${application.JSVERSION}"></script>
  <script
    th:src="${application.resourceUrl}+'/bboss/js/validator/bootstrapValidator-extend.js?'+${application.JSVERSION}"></script>
  <script
    th:src="${application.resourceUrl}+'/bboss/js/datatable/datatable_client.js?'+${application.JSVERSION}"></script>
  <script
    th:src="${application.resourceUrl}+'/bboss/js/datatable/datatable_server.js?'+${application.JSVERSION}"></script>
  <script th:src="${application.resourceUrl}+'/bboss/js/form/form.js?'+${application.JSVERSION}"></script>
  <script th:src="${application.resourceUrl}+'/assets/js/select2/select2.min.js?'+${application.JSVERSION}"></script>
  <script th:src="${application.resourceUrl}+'/bboss/js/select2/selectTab.js?'+${application.JSVERSION}"></script>
  <script th:src="${application.resourceUrl}+'/bboss/js/dialog/dialog-page.js?'+${application.JSVERSION}"></script>
  <script
    th:src="${application.resourceUrl}+'/bboss/js/dialog/bboss-dialog-page.js?'+${application.JSVERSION}"></script>
  <script
    th:src="${application.resourceUrl}+'/assets/js/jquery-file-upload/js/vendor/jquery.ui.widget.js?'+${application.JSVERSION}"></script>
  <script
    th:src="${application.resourceUrl}+'/assets/js/jquery-file-upload/js/jquery.iframe-transport.js?'+${application.JSVERSION}"></script>
  <script
    th:src="${application.resourceUrl}+'/assets/js/jquery-file-upload/js/jquery.fileupload.js?'+${application.JSVERSION}"></script>
  <script th:src="${application.resourceUrl}+'/assets/js/lightbox/js/lightbox.js?'+${application.JSVERSION}"></script>
  <script th:src="${application.resourceUrl}+'/bboss/js/upload/bboss-fileUpload.js?'+${application.JSVERSION}"></script>

  <script src="https://cdn.test.bestpay.net/orange/moment-with-locales.min.js"></script>
  <script src="https://cdn.test.bestpay.net/orange/vue.2.6.9.js"></script>
  <script src="https://cdn.test.bestpay.net/orange/antd.1.6.5.js"></script>
  <script src="https://cdn.test.bestpay.net/orange/axios.0.20.0.js"></script>
  <script src="https://cdn.test.bestpay.net/orange/antd-with-locales.1.6.5.js"></script>
  <script src="https://h5.test.bestpay.net/subapps/bboss/bboss/js/export/export-base.js?1.0.0"></script>
  <script src="./request.js"></script>

  <!--Page Related Scripts-->
  <script th:inline="javascript">
    function getBase64 (file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
      });
    }
    const { locales } = window.antd;
    /** 表格数据列配置 */
    const tableColumns = [
      {
        title: '商家ID',
        dataIndex: 'merchantId',
        align: 'center',
      },
      {
        title: '商家名称',
        dataIndex: 'merchantName',
        align: 'center',
      },
      {
        title: '配置时间',
        dataIndex: 'createdAt',
        align: 'center',
      },
      {
        title: '修改人',
        dataIndex: 'updatedBy',
        align: 'center',
      },
      {
        title: '操作',
        align: 'center',
        dataIndex: 'action',
        fixed: 'right',
        width: 250,
        scopedSlots: { customRender: 'action' },
      }
    ]

    const EditableCell = {
      template: `
          <div class="editable-cell">
            <div v-if="editable" class="flex justify-center items-center">
              <a-input :value="value" @change="handleChange" @pressEnter="check" />
              <a-icon type="check" class="ml-2" @click="check" />
            </div>
            <div v-else class="relative flex justify-center items-center px-8">
              {{ value || ' ' }}
              <a-icon v-if="!disableEdit" type="edit" class="absolute right-1 top-1/4" @click="edit" />
            </div>
          </div>
        `,
      props: {
        text: String,
        disableEdit: Boolean,
      },
      data () {
        return {
          value: this.text,
          editable: false,
        };
      },
      methods: {
        handleChange (e) {
          const value = e.target.value;
          this.value = value;
        },
        check () {
          this.editable = false;
          this.$emit('change', this.value);
        },
        edit () {
          this.editable = true;
        },
      },

    };
    moment.locale('zh-cn');
    var vm = new Vue({
      el: '#app',
      components: {
        EditableCell,
      },
      data: {
        editBtnLoading: false,
        dialogFormRules: {
          merchantName: [{ required: true, message: '请输入商家名称!', trigger: 'blur' }],
          productName: [{ required: true, message: '请输入所属产品!', trigger: 'blur' },],
          sceneName: [{ required: true, message: '请输入场景!', trigger: 'blur' }],

        },
        dialogFormDisabled: false,
        tableDetailColumns: [],
        tableScroll: { x: document.body.clientWidth * 0.8 },
        queryTableLoading: false,
        /** 展示 table 页面 */
        showTablePage: true,
        // table 数据
        /** 搜索栏样式配置 */
        layout: {
          labelCol: { span: 7 },
          wrapperCol: { span: 17 },
        },
        /** 搜索栏数据 */
        form: {
          // 商家ID
          merchantId: '',
          // 商户号
          merchantNo: '',
          // 商户名称
          merchantName: '',
        },
        // 活动周期  1单次 2不限次
        activityPeriodList: [
          {
            label: '单次',
            value: '1',
          },
          {
            label: '不限次',
            value: '2',
          },
        ],
        /** 分页器 */
        pagination: {
          showSizeChanger: true,
          showQuickJumper: true,
          total: null,
          pageSize: 10,
          current: 1,
          showTotal: (total, range) => `共${total}条`,
          pageSizeOptions: ['10', '25', '50', '100'],
          buildOptionText: (size) => {
            return `${size.value}条/页`
          }
        },
        /** 表格分页数据查询中标识位 */
        loading: false,
        /** 表格数据 */
        tableData: [],
        dialogFormTemp: {
          merchantNo: '',
          merchantName: '',
          ProductInfoVO: [{
            // 产品名称
            productName: '',
            sceneVOs: [{
              // 场景名称
              sceneName: ''
            }]
          }]
        },
        dialogForm: {
        },
        orderModalInfo: {}
      },
      mounted: function () {

        this.queryTableData();
      },
      methods: {
        onAddMerchantName (index) {
          this.dialogForm.ProductInfoVO.push({
            // 产品名称
            productName: '',
            sceneVOs: [{
              // 场景名称
              sceneName: ''
            }]
          })
        },
        onDelMerchantName (index) {
          this.dialogForm.ProductInfoVO.splice(index, 1)
        },
        onAddMerchantSceneVOs (index, i) {
          this.dialogForm.ProductInfoVO[index].sceneVOs.push({
            // 场景名称
            sceneName: ''
          })
        },
        onDelMerchantSceneVOs (index, i) {
          this.dialogForm.ProductInfoVO[index].sceneVOs.splice(i, 1)
        },
        /** 浏览图片 */
        catPhoto (url) {
          console.log("浏览图片", url)
          // position: absolute;left: 50%;top: 50%;transform: translate(-50%, -50%);max-width: 85vw;max-height: 85vh;
          let imgDom = "<div style='width: 100vw;position: fixed;left: 0;top: 0;z-index: 9999;height: 100vh;background: rgba(0,0,0,0.6);' >"
          imgDom += "<img src='" + url + "' style='position: absolute;left: 50%;top: 50%;transform: translate(-50%, -50%);max-width: 85vw;max-height: 85vh;' ></img>"
          imgDom += "</div>"
          const PicDom = $(imgDom)
          $("body").append(PicDom)
          PicDom.click(function () {
            $(this).remove();
          });

        },

        /** 上传照片处理 */
        photoInputChange (type) {
          const reader = new FileReader();
          const file = this.$refs[`${type}PhotoInput`].files[0];
          if (!file) {
            return;
          }

          reader.readAsDataURL(file);
          reader.onload = async (e) => {
            const url = '/PF/service/fastDfsServer/upload.upload';
            const form = new FormData();
            form.append('file', file);
            form.append('attachPath1', file.name.split('.')[1]);

            // 调用图片上传接口
            const res = await axios.post(url, form).finally(() => {
              this.$refs[`${type}PhotoInput`].value = '';
            });
            const { success, result, errorMsg } = JSON.parse(res.data);
            console.log(result, '图片上传接口');
            if (!success) {
              this.$message.error(errorMsg);
              return;
            }
            this.dialogForm[`${type}PhotoImgList`] = [{
              pictureUrl: result.fileUrl,
              fileGroup: result.fileGroup,
              fileName: result.fileName,
            }];
          }
        },

        // 新增活动
        onAddActivity () {

          this.dialogForm = { ...this.dialogFormTemp };
          this.showTablePage = false
        },
        goGoodsOrder (options) {
          console.log("options", options)
          const spuId = options.commodityVOs.spuId
          const orderNo = options.commodityOrderVO.orderNo
          location.href = location.origin + '/PF/page/mallOrderService/queryPage.html?spuId=' + spuId + '&orderNo=' + orderNo
        },
        /** 配置窗口按钮点击 */
        async dialogButtonClick (flag) {
          // 取消按钮直接重新展示table
          if (!flag) {
            this.showTablePage = true;
            return;
          }
        },
        onSubmit () {

          console.log("this.dialogForm", this.dialogForm)
          // 新增全部校验
          this.$refs.ruleForm.validate(async valid => {
            if (valid) {
              // this.onSubmitXhr()

              // activityStartTime: (this.form.activityTime && this.form.activityTime[0]) && moment(this.form.activityTime[0]).format('YYYY-MM-DD') + " 00:00:00",
              // activityEndTime: (this.form.activityTime && this.form.activityTime[1]) && moment(this.form.activityTime[1]).format('YYYY-MM-DD') + " 23:59:59",
            } else {
              console.log('error submit!!', valid);

              this.$message.error("表单校验出错，请校验表单");
              return false;
            }
          });
        },
        onQueryTableData () {
          this.pagination.current = 1
          this.queryTableData()
        },
        /** 查询表格数据 */
        async queryTableData () {
          console.log('查询表格数据');
          // 组装表格查询参数
          const searchTableDataParams = {
            ...this.form,
            size: this.pagination.pageSize,
            current: this.pagination.current,
            mobile: this.form.mobile,
            activityStartTime: (this.form.activityTime && this.form.activityTime[0]) && moment(this.form.activityTime[0]).format('YYYY-MM-DD') + " 00:00:00",
            activityEndTime: (this.form.activityTime && this.form.activityTime[1]) && moment(this.form.activityTime[1]).format('YYYY-MM-DD') + " 23:59:59",
          }
          delete this.form.activityTime
          // delete searchTableDataParams.mobile;
          for (let key in searchTableDataParams) {
            if (!searchTableDataParams[key]) {
              delete searchTableDataParams[key]
            }
          }
          console.log('表格查询参数', searchTableDataParams);
          // 数据查询
          const url = '/PF/service/excellentBlindBoxOrderService/blindBoxOrderQuery.do';
          this.queryTableLoading = true
          const { success, result, errorMsg } = await http.post(url, searchTableDataParams);
          this.queryTableLoading = false
          console.log(result, '查询表格数据');
          if (!success) {
            this.$message.error(errorMsg);
            return;
          }
          for (let i = 0; i < result.records.length; i++) {
            result.records[i].payAmount = result.records[i].payAmount / 100;
          }
          this.pagination.total = result.total,

            this.tableData = result.records;
        },
        // 导出
        onExport () {
          // /PF/service/excellentBlindBoxOrderService/blindBoxOrderExport.do
          const exportParams = [
            {
              "name": "targetFunctionId",
              "value": "PF#service#excellentBlindBoxOrderService#blindBoxOrderExport#do",
            },
            {
              "name": "fileCode",
              "value": "blindBoxOrderRecordExport",
            },
          ];
          if (this.form.activityTime && this.form.activityTime[0]) {
            $('#hiddenForm-startTime').val(moment(this.form.activityTime[0]).format('YYYY-MM-DD HH:mm:ss'))
          }
          if (this.form.activityTime && this.form.activityTime[1]) {
            $('#hiddenForm-endTime').val(moment(this.form.activityTime[1]).format('YYYY-MM-DD HH:mm:ss'))
          }
          const exportObj = new $.bboss.export.init(
            'export',
            'query-form',
            'dataList',
            'template-blindBoxOrderRecordExport.xlsx',
            '盲盒订单记录.xls',
            2000,
            2000,
            window,
            WWWROOT + "/PF/resource/excellentBlindBoxOrderService/export.download",
            null,
            exportParams,
          );
          exportObj.initForm();
          exportObj.startExport();
        },
        /** 重置搜索查询条件 */
        resetSearchFormInfo () {
          this.form = {};
          console.log('重置搜索查询条件');
        },
        /** 分页器事件处理 */
        handleTableChange (pagination) {
          // 设置分页器数据
          this.$set(this, 'pagination', pagination);
          // 查询 table 数据
          this.queryTableData();
        },
        /** 展示详情弹窗 */
        async showDetailDialog (record) {

          // 通过接口查询已配置商品信息
          const url = '/PF/service/excellentBlindBoxOrderService/blindBoxOrderDetailQuery.do';
          const params = {
            subOrderNo: record.subOrderNo,
          };
          console.log(params, '查询已配置商品信息参数');
          const { success, result, errorMsg } = await http.post(url, params);
          console.log(result, '查询已配置商品信息');
          if (!success) {
            this.$message.error(errorMsg);
            return;

          };
          this.dialogForm = { ...this.dialogFormTemp };
          // 清空一下搜索条件，方便新增或修改后再次查询内容
          // this.resetSearchFormInfo(); 
          this.showTablePage = false;
        },
      },
    });
  </script>
</body>
<!--  /Body -->

</html>